package com.salton123.soulove.biz_bmob.aty

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.TextView
import androidx.core.content.FileProvider
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.hjq.base.BaseDialog
import com.hjq.dialog.InputDialog
import com.hjq.dialog.WaitDialog
import com.hjq.toast.ToastUtils
import com.qw.soul.permission.SoulPermission
import com.qw.soul.permission.bean.Permission
import com.qw.soul.permission.callbcak.CheckRequestPermissionListener
import com.salton123.GlideApp
import com.salton123.soulove.api.ProviderManager
import com.salton123.arch.view.TitleBarStyle
import com.salton123.log.XLog
import com.salton123.soulove.biz_bmob.R
import com.salton123.soulove.biz_bmob.model.User
import com.salton123.soulove.common.Constants
import com.salton123.ui.base.BaseActivity
import com.salton123.utils.CropUtils
import kotlinx.android.synthetic.main.activity_personal_data.*
import java.io.File

/**
 * User: wujinsheng1@yy.com
 * Date: 2020/4/22 21:31
 * ModifyTime: 21:31
 * Description:
 */
@SuppressLint("CheckResult")
@Route(path = Constants.Router.User.PROFILE)
class ProfileActivity : BaseActivity() {

    companion object {
        private val TAG = "ProfileActivity"
        private val AVATAR_MAX_SIZE = 200
        private val REQUEST_CODE_TAKE_PHOTO = 1
        private val REQUEST_CODE_ALBUM = 2
        private val REQUEST_CODE_CROP_PHOTO = 3
    }

    val mBottomSheetDialog: BottomSheetDialog? by lazy {
        BottomSheetDialog(activity(), R.style.BottomSheetDialog)
    }

    override fun onRightClick(v: View?) {
        var path = Constants.Router.User.SETTING
        ARouter.getInstance().build(path)
            .navigation(activity())
    }

    override fun getRightText(): String {
        return getString(R.string.setting_title)
    }

    override fun getRightStyle(): Int {
        return TitleBarStyle.TEXT
    }

    var user = ProviderManager.user()?.getLoginUser()
    override fun initViewAndData(savedInstanceState: Bundle?) {
        GlideApp.with(activity())
            .load(user?.avatar?.url)
            .placeholder(R.drawable.ic_head_placeholder)
            .error(R.drawable.ic_head_placeholder)
            .circleCrop()
            .into(iv_person_data_avatar)
        sb_person_data_id.rightText = user?.objectId ?: ""
        sb_person_data_name.rightText = user?.nickname ?: ""
    }

    override fun initListener() {
        super.initListener()
        setListener(R.id.iv_person_data_avatar, R.id.sb_person_data_name)
    }

    override fun getLayoutId(): Int = R.layout.activity_personal_data

    override fun getTitleText(): String {
        return getString(R.string.personal_data_title)
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            R.id.iv_person_data_avatar -> {
                showClickPhotoDialog()
            }
            R.id.sb_person_data_name -> {
                InputDialog.Builder(this) // 标题可以不用填写
                    .setTitle(getString(R.string.personal_data_name_hint))
                    .setContent(sb_person_data_name.rightText)
                    .setHint(getString(R.string.personal_data_name_hint))
                    .setListener { _: BaseDialog?, content: String ->
                        if (sb_person_data_name.rightText != content) {
                            sb_person_data_name.rightText = content
                            ProviderManager.user()?.updateUserInfo(
                                hashMapOf(Pair("nickname", content))) {
                                if (it) {
                                    ToastUtils.show("昵称更新成功")
                                } else {
                                    ToastUtils.show("昵称更新失败")
                                }
                            }
                        }
                    }
                    .show()
            }
            else -> {
            }
        }
    }

    private fun showClickPhotoDialog() {
        val dialogView = View.inflate(activity(), R.layout.replace_avatar_dialog_layout, null)
        mBottomSheetDialog?.setContentView(dialogView)
        mBottomSheetDialog?.show()
        val choooseAlbum = dialogView.findViewById<TextView>(R.id.choseFromAlum)
        val takePhoto = dialogView.findViewById<TextView>(R.id.takePhoto)
        val cancel = dialogView.findViewById<TextView>(R.id.cancel)
        takePhoto.setOnClickListener {
            SoulPermission.getInstance().checkAndRequestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                object : CheckRequestPermissionListener {
                    override fun onPermissionOk(permission: Permission?) {
                        uploadAvatarFromPhotoRequest()
                    }

                    override fun onPermissionDenied(permission: Permission?) {
                        ToastUtils.show("请授予相应权限")
                    }
                })
            mBottomSheetDialog?.dismiss()
        }
        choooseAlbum.setOnClickListener {
            SoulPermission.getInstance().checkAndRequestPermission(Manifest.permission.CAMERA,
                object : CheckRequestPermissionListener {
                    override fun onPermissionOk(permission: Permission?) {
                        uploadAvatarFromAlbumRequest()
                    }

                    override fun onPermissionDenied(permission: Permission?) {
                        ToastUtils.show("请授予相应权限")
                    }
                })
            mBottomSheetDialog?.dismiss()
        }
        cancel.setOnClickListener {
            mBottomSheetDialog?.dismiss()
        }
    }

    private val uri: Uri? by lazy { getUri(activity()) }
    private val rootPath: String? by lazy { externalCacheDir?.toString() }
    private val avatarFile: File by lazy {
        File("$rootPath/avatar.jpg")
    }
    private var mSmallAvatarFile: File? = null
    private fun getUri(context: Context): Uri {
        val file = File(rootPath)
        if (!file.exists() || !file.isDirectory) {
            file.mkdirs()
        }
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            FileProvider.getUriForFile(context, context.packageName + ".fileprovider", avatarFile)
        } else {
            Uri.fromFile(avatarFile)
        }
    }

    /**
     * photo
     */
    private fun uploadAvatarFromPhotoRequest() {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0)
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
        startActivityForResult(intent,
            REQUEST_CODE_TAKE_PHOTO)
    }

    /**
     * album
     */
    private fun uploadAvatarFromAlbumRequest() {
        val pickIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        pickIntent.type = "image/*"
        var resolveInfos = packageManager?.queryIntentActivities(pickIntent,
            PackageManager.MATCH_DEFAULT_ONLY)
        if (resolveInfos != null && resolveInfos.size > 0) {
            startActivityForResult(pickIntent,
                REQUEST_CODE_ALBUM)
            return
        }

        val contentIntent = Intent()
        contentIntent.type = "image/*"
        contentIntent.action = Intent.ACTION_GET_CONTENT
        resolveInfos = packageManager?.queryIntentActivities(contentIntent, PackageManager
            .MATCH_DEFAULT_ONLY)
        if (resolveInfos != null && resolveInfos.size > 0) {
            startActivityForResult(Intent.createChooser(contentIntent, "Select Picture"),
                REQUEST_CODE_ALBUM)
        }
    }

    /**
     * 裁剪拍照裁剪
     *
     * @param uri
     */
    fun startPhotoZoom(uri: Uri?, fromCamera: Boolean) {
        val intent = Intent("com.android.camera.action.CROP")
        intent.setDataAndType(uri, "image/*")
        intent.putExtra("crop", "true") // crop=true 有这句才能出来最后的裁剪页面.
        intent.putExtra("aspectX", 1) // 这两项为裁剪框的比例.
        intent.putExtra("aspectY", 1) // x:y=1:1
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX",
            AVATAR_MAX_SIZE)
        intent.putExtra("outputY",
            AVATAR_MAX_SIZE)
        /**
         * 由于对返回的bitmap 有限制所以不能使用，return-data true ，需要本地搞个文件来存储下
         */
//        intent.putExtra("return-data", true)
        intent.putExtra(MediaStore.EXTRA_OUTPUT, getSmallUri())
        if (fromCamera) {
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        startActivityForResult(intent,
            REQUEST_CODE_CROP_PHOTO)
    }

    private fun getSmallUri(): Uri {
        val file = File(rootPath)
        if (!file.exists() || !file.isDirectory) {
            file.mkdirs()
        }
        mSmallAvatarFile = File("$rootPath/avatar_${System.currentTimeMillis()}.jpg")
        return Uri.fromFile(mSmallAvatarFile)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        try {
            if (resultCode != -1) {
                return
            }
            if (requestCode == REQUEST_CODE_ALBUM && data != null) {
                var newUri: Uri? = null
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    data.data?.let {
                        newUri = Uri.parse("file:///" + CropUtils.getPath(activity(), it))
                    }
                } else {
                    newUri = data.data
                }
                XLog.i(TAG, "onActivityResult ${newUri!!}")
                if (newUri != null) {
                    XLog.i(TAG, "onActivityResult ${newUri!!.path}")
                    startPhotoZoom(newUri, false)
                } else {
                    ToastUtils.show("照片读取失败")
                }
            } else if (requestCode == REQUEST_CODE_TAKE_PHOTO) {
                startPhotoZoom(uri, true)
            } else if (requestCode == REQUEST_CODE_CROP_PHOTO) {
                XLog.i(TAG, "$mSmallAvatarFile")
                mSmallAvatarFile?.absolutePath?.let { uploadAvatar(it) }
            }
        } catch (e: Exception) {
            XLog.i(TAG, "onActivityResult $e")
        }
    }

    private fun uploadAvatar(filePath: String) {
        if (filePath.isNotEmpty()) {
            showUploadDialog()
            ProviderManager.user()?.uploadAvatar(filePath) { ret, err ->
                if (ret) {
                    ToastUtils.show("头像上传成功")
                    GlideApp.with(activity())
                        .load(filePath)
                        .placeholder(R.drawable.ic_head_placeholder)
                        .error(R.drawable.ic_head_placeholder)
                        .circleCrop()
                        .into(iv_person_data_avatar)
                } else {
                    ToastUtils.show("头像上传失败，请稍后重试")
                }
                dismiss()

            }
        }
    }

    var waitDialog: BaseDialog? = null
    private fun showUploadDialog() {
        waitDialog = WaitDialog.Builder(this) // 消息文本可以不用填写
            .setMessage(getString(R.string.common_loading))
            .show()
    }

    private fun dismiss() {
        waitDialog?.dismiss()
        waitDialog = null
    }

    override fun onDestroy() {
        super.onDestroy()
        dismiss()
    }
}